package com.mzy.designMode.singletonPattern;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/6/6 10:04
 * @Version 1.0
 */

/**
 * 单例配置文件，保证可见性
 */
public class PropertiesLoader {
    private static PropertiesLoader singlePropertiesLoader = null;
    private Properties properties;
    private static final InputStream resourceAsStream = PropertiesLoader.class.getClassLoader().getResourceAsStream("application.properties");

    /**
     * 获取唯一实例
     */
    public static PropertiesLoader getInstance() {
        if (null == singlePropertiesLoader) {
            synchronized (PropertiesLoader.class) {
                if (null == singlePropertiesLoader) {
                    singlePropertiesLoader = new PropertiesLoader();
                }
            }
        }
        return singlePropertiesLoader;
    }

    /**
     * 构造方法
     */
    private PropertiesLoader() {
        properties = new Properties();
        try {
            // 通过类加载器，获取配置文件
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据key获取一个配置的值
     *
     * @param key
     * @return
     */
    public String getOneProp(String key) {
        return properties.getProperty(key);
    }

    /**
     * 获取配置文件对象
     */
    public Properties getProperties() {
        return properties;
    }

    /**
     * 回写properties文件对象
     */
    public void setProperties(Properties properties) throws IOException {
        this.properties = properties;
        URL resource = PropertiesLoader.class.getClassLoader().getParent().getResource("application.properties");
        URL resource1 = PropertiesLoader.class.getClassLoader().getResource("application.properties");
        ClassLoader parent = PropertiesLoader.class.getClassLoader().getParent();
        System.out.println(resource1.getPath());
        FileOutputStream fileOutputStream = new FileOutputStream(resource1.getPath());
        this.properties.store(fileOutputStream, "更新配置文件");
    }

    public String getPath() {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length());
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

}
